# -*- coding: utf-8 -*-
import hashlib
import json
import time
import uuid

import requests

YOUDAO_URL = 'https://openapi.youdao.com/api'
APP_KEY = '63ba4847d58a3642'
APP_SECRET = 'k1bD4lKefnflTlTM7wZhVxSDk6Ng3JNs'


def __encrypt(sign_str):
    hash_algorithm = hashlib.sha256()
    hash_algorithm.update(sign_str.encode('utf-8'))
    return hash_algorithm.hexdigest()


def __truncate(q):
    if q is None:
        return None
    size = len(q)
    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]


def __do_request(data):
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    return requests.post(YOUDAO_URL, data=data, headers=headers)


def connect(word="eg：请输入文字："):
    q = word

    data = {'from': 'zh-CHS', 'to': 'en', 'signType': 'v3'}
    current_time = str(int(time.time()))
    data['curtime'] = current_time
    salt = str(uuid.uuid1())
    signStr = APP_KEY + __truncate(q) + salt + current_time + APP_SECRET
    sign = __encrypt(signStr)
    data['appKey'] = APP_KEY
    data['q'] = q
    data['salt'] = salt
    data['sign'] = sign
    # data['vocabId'] = "您的用户词表ID"

    response = __do_request(data)
    contentType = response.headers['Content-Type']
    if contentType == "audio/mp3":
        millis = int(round(time.time() * 1000))
        filePath = "合成的音频存储路径" + str(millis) + ".mp3"
        fo = open(filePath, 'wb')
        fo.write(response.content)
        fo.close()
        return 'Listen to the tape'
    else:
        content = response.content
        decoder = json.loads(content)
        translation_ = decoder['translation']
        translation__ = translation_[0]
        return translation__
